<?php
class Model_Work
{
    static private $_table = 'work';
    
    public static function getCount()
    {
        $DB  = Eren_Registry::get('DB');
        $ret = $DB->table(self::$_table)
                  ->count();
        return $ret;
    }
    
    public static function getList($page)
    {
        $pagelimit = Model_Navigate::getLimit($page, Config_Default::getWorkPageSize());
        $DB  = Eren_Registry::get('DB');
        $ret = $DB->table(self::$_table)
                  ->orderBy('starttime', 'DESC')
                  ->limit($pagelimit['start'], $pagelimit['limit'])
                  ->select();
        return $ret['data'];
    }
    
    public static function getByID($workID)
    {
        $workID = intval($workID);
        $work = Eren_Registry::get('DB')->table(self::$_table)
                                        ->where('workid', '=', $workID)
                                        ->select();
        return !isset($work['data'][0])? array():$work['data'][0];
    }
    
    public static function getByModelName($modelName, $page)
    {
        $modelName = trim($modelName, "\r\n\t ");
        if(!Model_Validator::userName($modelName)){
            throw new Eren_Exception('模特名不合法，请填写正确的模特名，只能是字母、空格和数字', -1);
        }
        
        $pagelimit = Model_Navigate::getLimit($page, Config_Default::getWorkPageSize());

        $work = Eren_Registry::get('DB')->table(self::$_table)
                                        ->orderBy('starttime', 'DESC')
                                        ->where('modelname', 'LIKE', "%{$modelName}%")
                                        ->limit($pagelimit['start'], $pagelimit['limit'])
                                        ->select();
        return $work['data'];
    }
    
    public static function getCntByModelName($modelName)
    {
        $modelName = trim($modelName, "\r\n\t ");
        if(!Model_Validator::userName($modelName)){
            throw new Eren_Exception('模特名不合法，请填写正确的模特名，只能是字母、空格和数字', -1);
        }

        $ret = Eren_Registry::get('DB')->table(self::$_table)
                                        ->where('modelname', 'LIKE', "%{$modelName}%")
                                        ->count();
        return $ret;
    }
   
    public static function getByUserName($userName, $page)
    {
        $userName = trim($userName, "\r\n\t ");
        if(!Model_Validator::userName($userName)){
            throw new Eren_Exception('用户名不合法，请填写正确的用户名，只能是字母、空格和数字', -1);
        }

        $pagelimit = Model_Navigate::getLimit($page, Config_Default::getWorkPageSize());
        
        $work = Eren_Registry::get('DB')->table(self::$_table)
                                           ->orderBy('starttime', 'DESC')
                                        ->where('username', '=', $userName)
                                        ->limit($pagelimit['start'], $pagelimit['limit'])
                                        ->select();
        return $work['data'];
    }
    
    public static function getCntByUserName($userName)
    {
        $userName = trim($userName, "\r\n\t ");
        if(!Model_Validator::userName($userName)){
            throw new Eren_Exception('用户名不合法，请填写正确的用户名，只能是字母、空格和数字', -1);
        }

        $ret = Eren_Registry::get('DB')->table(self::$_table)
                                        ->where('username', '=', $userName)
                                        ->count();
        return $ret;
    }
    
    public static function getByTime($YM)
    {
        if(!Model_Validator::timeYM($YM)){
            throw new Eren_Exception('时间不合法', -1);
        }
        
        $bigDay = Model_Common::getMonthDays($YM);
        $start = Model_Common::getStampTime($YM . "-01");
        $end = Model_Common::getStampTime($YM . "-{$bigDay}");
        $work = Eren_Registry::get('DB')->table(self::$_table)
                                        ->orderBy('starttime,starthour', 'ASC')
                                        ->where('starttime', '<=', $end)
                                        ->wAND()
                                        ->where('endtime', '>=', $start)
                                        ->select();
        return $work['data'];
    }
    
    public static function getByStartEndTime($starttime, $endtime, $workid)
    {
        if(!Model_Validator::timeYMD($starttime)){
            throw new Eren_Exception('开始时间不合法', -1);
        }
    	if(!Model_Validator::timeYMD($endtime)){
            throw new Eren_Exception('结束时间不合法', -1);
        }
        
        $start = Model_Common::getStampTime($starttime);
        $end = Model_Common::getStampTime($endtime);
        $work = Eren_Registry::get('DB')->table(self::$_table)
                                        ->orderBy('starttime,starthour', 'ASC')
                                        ->where('starttime', '<=', $end)
                                        ->wAND()
                                        ->where('endtime', '>=', $start)
                                        ->wAND()
                                        ->where('workid', '!=', $workid)
                                        ->select();
        return $work['data'];
    }
    
    public static function add($username, $starttime, $endtime, $starthour, $endhour, 
                            $flg, $modelname, $info, $notice, $worktype, $perprice, 
                            $price, $pricetime, $customername, $customertel, $customerothertel, 
                            $customeraddress, $hour, $prepricetime, $companyname,$cost, $tax, $pay, 
                            $profit, $workaddress, $sure, $ret, $startmin, $endmin)
    {
        if(!Model_User::ifUserNameExist($username)){
        	throw new Eren_Exception('经纪人不存在,请确认名字是否正确', -1);
        }
        
        if($sure != 0 && $sure != 1){
        	throw new Eren_Exception('是否待定异常', -1);
        }
    	
        if(!Model_Validator::timeYMD($starttime)){
            throw new Eren_Exception('开始时间不合法', -1);
        }
        $starttime = Model_Common::getStampTime($starttime);
        
        if(!Model_Validator::timeYMD($endtime)){
            throw new Eren_Exception('结束时间不合法', -1);
        }
        $endtime = Model_Common::getStampTime($endtime);
        
        $nowDay = Model_Common::getStampTime(Model_Common::getFormatTimeYMD());
        if(Model_User::getLevelID() != 5){
	        if($starttime < $nowDay || $endtime < $nowDay){
	        	throw new Eren_Exception('开始、结束时间都不可小于今天', -1);
	        }
        }
        
        if($starttime > $endtime){
            throw new Eren_Exception('开始日期不能大于结束日期', -1);
        }
        
        $starthour = intval($starthour);
        $endhour = intval($endhour);
        $startmin = intval($startmin);
        $endmin = intval($endmin);
        $tStartTime = $starthour*60 + $startmin;
        $tEndTime = $endhour*60 + $endmin;
        if($tStartTime >= $tEndTime){
            throw new Eren_Exception('结束时间不能小于开始时间', -1);
        }
        
        $flg = intval($flg);
        if($flg !=1 && $flg != 2){
            throw new Eren_Exception('工作面试信息异常', -1);
        }
        
        $companyname = Model_Common::filterText($companyname);
        if($companyname == ""){
            throw new Eren_Exception('客户名称不能为空', -1);
        }
        
        $notice = Model_Common::filterText($notice);
        
        $workTypes = Config_Default::getWorkType();
        if(!isset($workTypes[$worktype])){
            throw new Eren_Exception('工作类型异常', -1);
        }
        
        if(!Model_Validator::price($perprice)){
            throw new Eren_Exception('收费单价异常，请填写数字', -1);
        }
        
        if(!Model_Validator::timeYMD($prepricetime)){
            throw new Eren_Exception('预计回款时间异常，请正确填写', -1);
        }
        $prepricetime = Model_Common::getStampTime($prepricetime);
        if(Model_User::getLevelID() != 5){
	        if($prepricetime < $nowDay){
	        	throw new Eren_Exception('预计回款时间不能小于今天，请正确填写', -1);
	        }
        }
        
        $customername = Model_Common::filterText($customername);
        if($customername == ""){
            throw new Eren_Exception('客户联系人不能为空，请正确填写', -1);
        }
        
        if(!Model_Validator::tel($customertel)){
            throw new Eren_Exception('手机号格式错误，请填写11位数字', -1);
        } 

        $customeraddress = Model_Common::filterText($customeraddress);
        if($customeraddress == ""){
            throw new Eren_Exception('客户地址不能为空', -1);
        }
        
        $workaddress = Model_Common::filterText($workaddress);
        if($workaddress == ""){
            throw new Eren_Exception('工作地址不能为空', -1);
        }
        
        $fields['sure']                = $sure;
        $fields['username']            = $username;                        
        $fields['starttime']           = $starttime;
        $fields['endtime']             = $endtime;
        $fields['starthour']           = $starthour;
        $fields['endhour']             = $endhour;
        $fields['startmin']            = $startmin;
        $fields['endmin']              = $endmin;
        $fields['flg']                 = $flg;
        $fields['modelname']           = $modelname;
        $fields['info']                = $info;
        $fields['notice']              = $notice;
        $fields['worktype']            = $worktype;
        $fields['perprice']            = $perprice;
        $fields['customername']        = $customername;
        $fields['customertel']         = $customertel;
        $fields['customerothertel']    = $customerothertel;
        $fields['customeraddress']     = $customeraddress;  
        $fields['workaddress']         = $workaddress;  
        $fields['companyname']         = $companyname;
        $fields['hour']                = $hour;
        $fields['prepricetime']        = $prepricetime;        
        $fields['createdtime']         = Model_Common::getNowTime();
        
        
        if(Model_User::getLevelID() == 5){
	        if($price != '' && !Model_Validator::price($price)){
	            throw new Eren_Exception('实际回款异常，请填写数字', -1);
	        }
	        if($pricetime != '' && !Model_Validator::timeYMD($pricetime)){
	            throw new Eren_Exception('实际回款时间异常，请正确填写', -1);
	        }
	        if($pricetime != ''){
	        	$pricetime = Model_Common::getStampTime($pricetime);
	        }else{
	        	$pricetime = 0;
	        }
	        if($cost != '' && !Model_Validator::price($cost)){
	            throw new Eren_Exception('成本异常，请填写数字', -1);
	        }
       		if($tax != '' && !Model_Validator::price($tax)){
	            throw new Eren_Exception('税款异常，请填写数字', -1);
	        }
     		if($pay != '' && !Model_Validator::price($pay)){
	            throw new Eren_Exception('提成异常，请填写数字', -1);
	        }
            if($ret != '' && !Model_Validator::price($ret)){
	            throw new Eren_Exception('客户返款异常，请填写数字', -1);
	        }
            if($profit != '' && !Model_Validator::price($profit)){
	            throw new Eren_Exception('利润异常，请填写数字', -1);
	        }
	        $fields['price']    = $price;
	        $fields['pricetime']= $pricetime;
	        $fields['cost']     = $cost;  
	        $fields['tax']      = $tax;
	        $fields['pay']      = $pay;
	        $fields['ret']      = $ret;
	        $fields['profit']   = $profit;  
        }

        $ret = Eren_Registry::get('DB')->table(self::$_table)->insert($fields);
        $log = var_export($fields, true);
        Model_Log::write("[workid:{$ret}][add][{$log}]");
        return $ret;
    }
    
    public static function update($workID, $starttime, $endtime, $starthour, $endhour, 
                            $flg, $modelname, $info, $notice, $worktype, $perprice, 
                            $price, $pricetime, $customername, $customertel, $customerothertel, 
                            $customeraddress, $hour, $prepricetime, $companyname, $cost, $tax, $pay, 
                            $profit, $workaddress, $sure, $ret, $startmin, $endmin)
    {
        $workID = intval($workID);
        $work = self::getByID($workID);
        if(empty($work)){
            throw new Eren_Exception('更新的工作不存在', -1);
        }
        
        if($sure != 0 && $sure != 1){
        	throw new Eren_Exception('是否待定异常', -1);
        }
        
        if(!Model_Validator::timeYMD($starttime)){
            throw new Eren_Exception('开始时间不合法', -1);
        }
        $starttime = Model_Common::getStampTime($starttime);
        
        if(!Model_Validator::timeYMD($endtime)){
            throw new Eren_Exception('结束时间不合法', -1);
        }
        $endtime = Model_Common::getStampTime($endtime);
        
        $nowDay = Model_Common::getStampTime(Model_Common::getFormatTimeYMD());
        /*if(Model_User::getLevelID() != 5){
	        if($starttime < $nowDay || $endtime < $nowDay){
	        	throw new Eren_Exception('开始、结束时间都不可小于今天', -1);
	        }
        }*/
        
        if($starttime > $endtime){
            throw new Eren_Exception('开始日期不能大于结束日期', -1);
        }
        
        $starthour = intval($starthour);
        $endhour = intval($endhour);
        $startmin = intval($startmin);
        $endmin = intval($endmin);
        $tStartTime = $starthour*60 + $startmin;
        $tEndTime = $endhour*60 + $endmin;
        if($tStartTime >= $tEndTime){
            throw new Eren_Exception('结束时间不能小于开始时间', -1);
        }
        
        $flg = intval($flg);
        if($flg !=1 && $flg != 2){
            throw new Eren_Exception('工作面试信息异常', -1);
        }
        
        $companyname = Model_Common::filterText($companyname);
        if($companyname == ""){
            throw new Eren_Exception('客户名称不能为空', -1);
        }
        
        $notice = Model_Common::filterText($notice);
        
        $workTypes = Config_Default::getWorkType();
        if(!isset($workTypes[$worktype])){
            throw new Eren_Exception('工作类型异常', -1);
        }
        
        if(!Model_Validator::price($perprice)){
            throw new Eren_Exception('收费单价异常，请填写数字', -1);
        }
        
        if(!Model_Validator::timeYMD($prepricetime)){
            throw new Eren_Exception('预计回款时间异常，请正确填写', -1);
        }
        $prepricetime = Model_Common::getStampTime($prepricetime);
    	/*if(Model_User::getLevelID() != 5){
	        if($prepricetime < $nowDay){
	        	throw new Eren_Exception('预计回款时间不能小于今天，请正确填写', -1);
	        }
        }*/
        
        $customername = Model_Common::filterText($customername);
        if($customername == ""){
            throw new Eren_Exception('客户联系人不能为空，请正确填写', -1);
        }
        
        if(!Model_Validator::tel($customertel)){
            throw new Eren_Exception('手机号格式错误，请填写11位数字', -1);
        } 

        $customeraddress = Model_Common::filterText($customeraddress);
        if($customeraddress == ""){
            throw new Eren_Exception('客户地址不能为空', -1);
        }
        
        $workaddress = Model_Common::filterText($workaddress);
        if($workaddress == ""){
            throw new Eren_Exception('工作地址不能为空', -1);
        }
                            
        $fields['sure']                = $sure;
        $fields['starttime']           = $starttime;
        $fields['endtime']             = $endtime;
        $fields['starthour']           = $starthour;
        $fields['endhour']             = $endhour;
        $fields['startmin']            = $startmin;
        $fields['endmin']              = $endmin;
        $fields['flg']                 = $flg;
        $fields['modelname']           = $modelname;
        $fields['info']                = $info;
        $fields['notice']              = $notice;
        $fields['worktype']            = $worktype;
        $fields['perprice']            = $perprice;
        $fields['customername']        = $customername;
        $fields['customertel']         = $customertel;
        $fields['customerothertel']    = $customerothertel;
        $fields['customeraddress']     = $customeraddress;
        $fields['workaddress']         = $workaddress;  
		$fields['companyname']         = $companyname;
        $fields['hour']                = $hour;
        $fields['prepricetime']        = $prepricetime;   
        
   		if(Model_User::getLevelID() == 5){
   			if($price != '' && !Model_Validator::price($price)){
	            throw new Eren_Exception('实际回款异常，请填写数字', -1);
	        }
	        if($pricetime != '' && !Model_Validator::timeYMD($pricetime)){
	            throw new Eren_Exception('实际回款时间异常，请正确填写', -1);
	        }
	        if($pricetime != ''){
	        	$pricetime = Model_Common::getStampTime($pricetime);
	        }else{
	        	$pricetime = 0;
	        }
	        if($cost != '' && !Model_Validator::price($cost)){
	            throw new Eren_Exception('成本异常，请填写数字', -1);
	        }
       		if($tax != '' && !Model_Validator::price($tax)){
	            throw new Eren_Exception('税款异常，请填写数字', -1);
	        }
     		if($pay != '' && !Model_Validator::price($pay)){
	            throw new Eren_Exception('提成异常，请填写数字', -1);
	        }
   		    if($ret != '' && !Model_Validator::price($ret)){
	            throw new Eren_Exception('客户返款异常，请填写数字', -1);
	        }
            if($profit != '' && !Model_Validator::price($profit)){
	            throw new Eren_Exception('利润异常，请填写数字', -1);
	        }
	        $fields['price']    = $price;
	        $fields['pricetime']= $pricetime;
	        $fields['cost']     = $cost;  
	        $fields['tax']      = $tax;
	        $fields['pay']      = $pay;
	        $fields['ret']      = $ret;
	        $fields['profit']   = $profit;  
        }
        
        Eren_Registry::get('DB')->table(self::$_table)->where('workid', '=', $workID)->update($fields);
        $log = var_export($fields, true);
        Model_Log::write("[workid:{$workID}][update][{$log}]");
        return TRUE;
    }
    
    public static function delete($workID)
    {
        $workID     = intval($workID);
        $work = self::getByID($workID);
        if(empty($work)){
            throw new Eren_Exception('删除的工作不存在', -1);
        }
        
        Eren_Registry::get('DB')->table(self::$_table)->where('workid', '=', $workID)->delete();
        Model_Log::write("[workid:{$workID}][delete]");
        return TRUE;
    }
    
    public static function ifAuthModify($work)
    {
    	if(Model_User::getLevelID() == 5){
    		return true;
    	}else if(Model_User::getLevelID() == 4 || 
    			((Model_User::getLevelID() == 3 || Model_User::getLevelID() == 2) && Model_User::getUserName() == $work['username'])){
	    	$now = Model_Common::getStampTime(Model_Common::getFormatTimeYMD());
	    	if($now >= $work['endtime'] + 3*24*60*60){
	    		return false;
	    	}
	    	return true;
    	}
    	
    	return false;
    }
    
    public static function ifAuthDetail($work)
    {
    	if(Model_User::getLevelID() == 5 || Model_User::getLevelID() == 4){
    		return true;
    	}
        if((Model_User::getLevelID() == 3 || Model_User::getLevelID() == 2) && 
        					strtolower($work['username']) == strtolower(Model_User::getUserName())){
            return true;
        }
        /*if(Model_User::getLevelID() == 1 && stristr(strtolower($work['modelname']), strtolower(Model_User::getUserName()))){
            return true;
        }*/
        
        return false;
    }
}
